package com.canton.service.impl;
import java.util.*;
import com.canton.dao.entity.GrapeNode;
import com.canton.dao.entity.ImageNode;
import com.canton.dao.repository.GrapeRepository;
import com.canton.service.GrapeService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;



@Service
public class GrapeServiceImpl implements GrapeService {

    @Autowired
    private GrapeRepository grapeRepository;
//    @Autowired
//    private GrapeService grapeService;


private Map<String, Object> toD3Format(Collection<GrapeNode> movies) {
    List<Map<String, Object>> nodes = new ArrayList<>();
    List<Map<String, Object>> rels = new ArrayList<>();
    int i = 0;
    Iterator<GrapeNode> result = movies.iterator();
    while (result.hasNext()) {
        GrapeNode grapeNode = result.next();
        nodes.add(map("title", grapeNode.getName(), "label", "movie"));
        int target = i;
        i++;
        for (ImageNode imageNode : grapeNode.getImages()) {
            Map<String, Object> image = map("title", grapeNode.getName(), "label", "actor");
            int source = nodes.indexOf(image);
            if (source == -1) {
                nodes.add(image);
                source = i++;
            }
            rels.add(map("source", source, "target", target));
        }
    }
    return map("nodes", nodes, "links", rels);
}
    private Map<String, Object> map(String key1, Object value1, String key2, Object value2) {
        Map<String, Object> result = new HashMap<String, Object>(2);
        result.put(key1, value1);
        result.put(key2, value2);
        return result;
    }
    @Override
    public GrapeNode findByName(String name) {
        return grapeRepository.findByName(name);
    }

    @Override
    public List<GrapeNode> findAll() {
        return grapeRepository.findAll();
    }

    @Override
    public List<GrapeNode> findByNameLike(String likes) {
        return grapeRepository.findByNameLike(likes);
    }

    @Override
    public Map<String, Object> graph(int limit) {
        return null;
    }

//    @Override
//    public Map<String, Object> graph(int limit) {
//        Collection<GrapeNode> result = grapeRepository.findAllLimitBy(limit);
//        return toD3Format(result);
//    }
}
